跳到主要内容

Unity 打包 WebGL 相关

与外部 JS 交互

参考资料 官方文档 WebGL:与浏览器脚本交互 参考资料 unity 和 WebGL 互调传值

Unity 调用 JavaScript

在项目中使用浏览器 JavaScript 的建议方法是将 JavaScript 源代码添加到项目中,然后直接从脚本代码中调用这些函数

使用 .jslib 扩展名将包含 JavaScript 代码的文件放置在 Assets 文件夹中的 “Plugins” 子文件夹下,插件文件需要有如下所示的语法:

mergeInto(LibraryManager.library, {

Hello: function () {
window.alert("Hello, world!");
},

HelloString: function (str) {
window.alert(Pointer_stringify(str));
},

PrintFloatArray: function (array, size) {
for(var i = 0; i < size; i++)
console.log(HEAPF32[(array >> 2) + i]);
},

AddNumbers: function (x, y) {
return x + y;
},

StringReturnValueFunction: function () {
var returnStr = "bla";
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
},

BindWebGLTexture: function (texture) {
GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]);
},

});

然后,可从 C# 脚本调用这些函数,如下所示:

using UnityEngine;
using System.Runtime.InteropServices;

public class NewBehaviourScript : MonoBehaviour {

[DllImport("__Internal")]
private static extern void Hello();

[DllImport("__Internal")]
private static extern void HelloString(string str);

[DllImport("__Internal")]
private static extern void PrintFloatArray(float[] array, int size);

[DllImport("__Internal")]
private static extern int AddNumbers(int x, int y);

[DllImport("__Internal")]
private static extern string StringReturnValueFunction();

[DllImport("__Internal")]
private static extern void BindWebGLTexture(int texture);

void Start() {
Hello();

HelloString("This is a string.");

float[] myArray = new float[10];
PrintFloatArray(myArray, myArray.Length);

int result = AddNumbers(5, 7);
Debug.Log(result);

Debug.Log(StringReturnValueFunction());

var texture = new Texture2D(0, 0, TextureFormat.ARGB32, false);
BindWebGLTexture(texture.GetNativeTextureID());
}
}

JavaScript 调用 Unity

从浏览器的 JavaScript 向 Unity 脚本发送一些数据或通知。建议的做法是调用内容中的游戏对象上的方法

// 这个 unityInstance 就是全局 Unity 对象

// objectName 是场景上的对象名
// methodName 是挂载在对象上面的方法名称
unityInstance.SendMessage(objectName, methodName, value);

// 例:
unityInstance.SendMessage('MyGameObject', 'MyFunction');
unityInstance.SendMessage('MyGameObject', 'MyFunction', 5);
unityInstance.SendMessage('MyGameObject', 'MyFunction', 'MyString');

Unity发布WebGl注意事项

参考资料 Unity发布WebGl注意事项

自定义 WebGL 模板

参考资料 使用 WebGL 模板 参考资料 Unity WebGL 开发(一)